<template>
  <div style="margin-right: 30px;">
    <el-form
        label-width="150px"
        :rules="rules"
        ref="formObj"
        :model="payform">
      <el-form-item label="请选择缴费种类"  prop="type">
        <el-radio-group v-model="payform.type">
          <el-radio label="水费" >水费</el-radio>
          <el-radio label="电费">电费</el-radio>
          <el-radio label="燃气费">燃气费</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="请选择缴费金额"  prop="amount">
        <el-radio-group v-model="payform.amount">
          <el-radio :label="10">￥10</el-radio>
          <el-radio :label="20">￥20</el-radio>
          <el-radio :label="50">￥50</el-radio>
          <el-radio :label="100">￥100</el-radio>
          <el-radio :label="200">￥200</el-radio>
          <el-radio :label="500">￥500</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="密码(同登录密码)" prop="password">
        <el-input v-model="payform.password" style="width: 240px" type="password" placeholder="请输入您的密码"
                  show-password clearable />
      </el-form-item>

      <br/>
      <el-form-item>
        <el-button type="primary" @click="save()" plain>确认支付</el-button>
        <el-button type="danger" @click="reset()" plain>重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { get, post } from '@/plugins/axios'
import { reactive, ref } from 'vue'
import { getCookieForObject, setCookiesFromObject } from '@/util';
import {_axios} from '@/plugins/axios'
import {ElMessageBox} from 'element-plus'
import { ElForm, ElMessage } from 'element-plus';
import router from '@/router/index'

const account = ref(0) // 数据库中的余额
const props = defineProps({
  id: String,
  electricity: Number,
  water: Number,
  gas: Number, // 新增燃气费
  show: Boolean
})
const formObj = ref()
const tel = ref('')
const newmoney = ref(0)
const emits = defineEmits(['update:show', 'update:electricity', 'update:water', 'update:gas', 'getTableData'])
const userId = getUserId()
const payif = ref(0)
const payform = reactive({
  name: '',
  type: '',
  amount: '',
  password: ''
})

function getUserId() {
  const userinfo = getCookieForObject('user')
  account.value = userinfo.account
  return userinfo.id
}

function init() {
  const user = getCookieForObject('user')
  account.value = user.account
  tel.value = user.phone
}

function handleRecharge() {
  newmoney.value = Number(account.value) - Number(payform.amount)
  console.dir("运算结果" + newmoney.value)
}

function save() {
  handleRecharge()

  // 公共余额检查
  if (newmoney.value < 0) {
    ElMessageBox.confirm(
        '您的账户余额不足，是否跳转到充值部分？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
    ).then(() => {
      router.push({ name: 'Recharge-Transfer' });
    });
    return
  }

  // 根据不同费用类型处理
  let apiEndpoint = '';
  let updateEvent = '';

  switch(payform.type) {
    case "水费":
      apiEndpoint = '/tUser/paywater';
      updateEvent = 'update:water';
      break;
    case "电费":
      apiEndpoint = '/tUser/payelectricity';
      updateEvent = 'update:electricity';
      break;
    case "燃气费":
      apiEndpoint = '/tUser/paygas';
      updateEvent = 'update:gas';
      break;
    default:
      ElMessage.error('请选择缴费类型');
      return;
  }

  // 验证密码
  post('/tUser/paycheck', {
    id: userId,
    password: payform.password,
    paymoney: payform.amount
  }, res => {
    if (res) {
      // 更新账户余额
      const user = getCookieForObject('user')
      user.account = newmoney.value
      setCookiesFromObject('user', user)

      // 发送支付请求
      const formData = new FormData()
      for (const key in payform) {
        formData.append(key, payform[key])
      }
      formData.append('id', userId)
      formData.append('qian', payform.amount)

      _axios.request({
        url: apiEndpoint,
        method: 'post',
        data: formData
      }).then(response => {
        ElMessage.success(payform.type + '支付成功')

        // 更新对应费用余额
        if (payform.type === "水费") {
          emits(updateEvent, Number(props.water) + Number(payform.amount))
        } else if (payform.type === "电费") {
          emits(updateEvent, Number(props.electricity) + Number(payform.amount))
        } else if (payform.type === "燃气费") {
          emits(updateEvent, Number(props.gas) + Number(payform.amount))
        }

        // 关闭对话框并刷新数据
        emits('getTableData')
        emits('update:show', false)

        // 添加缴费记录
        waterin()
      }).catch(error => {
        ElMessage.error(payform.type + '支付失败：' + error.message)
      })
    }
  }, formObj)
}

function waterin() {
  post('/bill/add', { userId: userId, type: payform.type, amount: payform.amount }, res => {
    emits('update:show', false)
    emits('getTableData')
  })
  console.log(payform.amount)
}

function reset() {
  payform.name = '',
      payform.password = ''
  payform.type = ''
  payform.amount = ''
}

const rules = reactive({
  password: [
    { required: true, message: '请输入您的密码', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择缴费类型', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请选择缴费金额', trigger: 'change' }
  ]
})
</script>

<style scoped lang="scss">
</style>